package edu.neu.javaweb.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 这个类的作用是实现
 * 如果已登录用户回头访问了 login 或者 login.html
 * 就直接跳去欢迎页面
 */
@WebFilter(urlPatterns = {
        "/login.html",
        "/login"
})
public class LoginJumperFilter implements Filter {

    final Logger log = LoggerFactory.getLogger(this.getClass().getName());

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("login jumper filter");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        HttpSession session = httpServletRequest.getSession(); // 如果是第一次来login，那这一步就能够设置session
        log.info(session.getId());
        Object isLoginSession = session.getAttribute("isLogin");
        if (isLoginSession != null) {
            if ((Boolean) isLoginSession == true) {
                // 如果是已经登录的会话又回来访问login页面，那就直接跳到别处
                log.info("已登录，直接跳转");
                httpServletResponse.sendRedirect("pages/welcome.html");
                return;
            }
        } else {
            // 如果还没有isLogin属性，说明第一次登录，设一个false然后执行login逻辑
            httpServletRequest.getSession().setAttribute("isLogin", false);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
